package com.cuijq.ms.clone.v6;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.List;

/**
 * @Classname Demo
 * @Description TODO
 * @Date 2021/5/14 16:49
 * @Created by CuiJQ
 */
public class Demo {

  private HashMap<String, SearchWord> currentKeywords = new HashMap<>();
  private long lastUpdateTime = -1;

  public void refresh() throws IOException, ClassNotFoundException {
    // 原型模式就这么简单，拷贝已有对象的数据，更新少量差值
    /**
     * 这里分为深拷贝 和 浅拷贝。
     * 浅拷贝 得到的数据 与原始对象 共享数据
     * 深拷贝 得到的数据 是完完全全独立的对象
     */
// Deep copy

    // Shallow copy
    HashMap<String, SearchWord> newKeywords = (HashMap) currentKeywords.clone();

    // 从数据库中取出更新时间>lastUpdateTime的数据，放入到newKeywords中
    List<SearchWord> toBeUpdatedSearchWords = getSearchWords(lastUpdateTime);
    long maxNewUpdatedTime = lastUpdateTime;
    for (SearchWord searchWord : toBeUpdatedSearchWords) {
      if (searchWord.getLastUpdateTime() > maxNewUpdatedTime) {
        maxNewUpdatedTime = searchWord.getLastUpdateTime();
      }
      //先判断是否包含，如果包含remove
      if (newKeywords.containsKey(searchWord.getKeyword())) {
        newKeywords.remove(searchWord.getKeyword());
      }
      //从新put
      newKeywords.put(searchWord.getKeyword(), searchWord);
    }
    lastUpdateTime = maxNewUpdatedTime;
    currentKeywords = newKeywords;
  }

  private List getSearchWords(long lastUpdateTime) {
    // TODO: 从数据库中取出更新时间>lastUpdateTime的数据
    return null;
  }

  //深拷贝都要比浅拷贝耗时、耗内存空间
  //先将对象序列化，然后再反序列化成新的对象。
  public Object deepCopy(Object object) throws IOException, ClassNotFoundException {
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    ObjectOutputStream oo = new ObjectOutputStream(bo);
    oo.writeObject(object);
    ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
    ObjectInputStream oi = new ObjectInputStream(bi);
    return oi.readObject();
  }
}
